﻿using System;
using System.Collections.Generic;
using System.Text;

namespace KataProfiler
{
    class KPMessage
    {
        public enum KPMessageType
        {
            KMT_SUCCESS = 0,
            KMT_FAILED,

            KMT_FINISH_CAPTURE,

            KMT_OBJECT_TEXTURE,
            KMT_OBJECT_SHADER,
            KMT_OBJECT_PROGRAM,

            KMT_GL_GEN_TEXTURES,
            KMT_GL_BIND_TEXTURE,

            KMT_GL_DRAW_ARRAYS,

            KMT_NONE
        }

        public int m_offset;

        public int m_type;
        public int m_length;
        public byte[] m_pData;

        public KPMessage()
        {
            m_offset = 0;
            m_type = 0;
            m_length = 0;
            m_pData = null;
        }

        public int consume(byte[] buffer, int offsetStart, int offsetEnd)
        {
            int count = offsetEnd - offsetStart + 1;
            
            if (m_offset >= 8)
            {
                int k = Math.Min(m_length + 8 - m_offset, count);
                Utils.memcpy(m_pData, m_offset - 8, buffer, offsetStart, k);

                m_offset += k;
                return k;
            }

            if (m_offset < 4)
            {
                int k = Math.Min(4 - m_offset, count);
                for (int x = m_offset; x < m_offset + k; x++)
                {
                    m_type = Utils.setByte(m_type, x, buffer[offsetStart + x - m_offset]);
                }

                m_offset += k;
                return k;
            }

            int t = Math.Min(8 - m_offset, count);
            for (int x = m_offset; x < m_offset + t; x++)
            {
                m_length = Utils.setByte(m_length, x - 4, buffer[offsetStart + x - m_offset]);
            }

            m_offset += t;

            if (m_offset >= 8 && m_length > 0 && m_pData == null)
            {
                m_pData = new byte[m_length];
            }

            return t;
        }

        public bool isFull()
        {
            return m_offset >= 8 && m_offset == 8 + m_length;
        }

        public bool isFinishCaptureMessage()
        {
            Utils.assert(isFull());
            return m_type == (int) KPMessageType.KMT_FINISH_CAPTURE;
        }
    }
}
